/**
 * wap 全局 js文件
 * @authors supmain (mtingfeng@gmail.com)
 * @date    2014-12-01 11:53:04
 * @for *.html
 * @version $1.0$
 */
var $window = $(window);
var BST = {
	init: function(){

    },
    check: {
        //判断是否为中英文，数字，下划线，减号
        isNick: function(str) {
            var nickReg = /^[\u4e00-\u9fa5A-Za-z0-9-_]+$/;
            return nickReg.test(str);
        },
        //判断邮箱
        isEmail: function(str) {
            var emailReg = /^[a-z0-9][\w\.]*@([a-z0-9][a-z0-9-]*\.)+[a-z]{2,5}$/i;
            return emailReg.test(str);
        },
        //判断手机
        isMobile: function(str) {
            var mobileReg = /^1[34578][0-9]{9}$/;
            return mobileReg.test(str);
        },
        //判断URL
        isUrl: function(str) {
            var urlReg = /^http:\/\/([\w-]+\.)+[\w-]+(\/[\w-.\/?%&=]*)?$/;
            return urlReg.test(str);
        },
        //判断数字
        isNum: function(str) {
            var numReg = /^[0-9]\d*$/;
            return numReg.test(str);
        }
    },

    dialog: {

        $confirm: null,

        confirm: function(html,callback,initFn){
            var $confirm = null;
            if(this.$confirm !== null || $('#dg-tip').length>0){
                return;
            }else{
                $confirm = $('<div id="dg-confirm"><div class="dg_body"><div class="dg_box"><i class="iconfont blue">&#xe62b;</i>'+html+'</div><div class="btm"><a href="javascript:BST.dialog.close();" class="graybtn">取消</a><a href="javascript:;" class="btn">确定</a></div></div></div>');
            }
            $confirm.appendTo('body').addClass('pop_in');
            this.$confirm = $confirm;
            BST.pageScroll.stop();
            $confirm.on('click','a.btn',function(){
                setTimeout(function(){
                    callback();
                }, 50);
                return false;
            });

            initFn && initFn();
        },

        close: function(){
            var that = this,
                $confirm = that.$confirm;
            if($confirm === null){
                return;
            }else{
                $confirm.addClass('pop_out');
                setTimeout(function(){
                    $confirm.off().remove();
                    that.$confirm = null;
                    BST.pageScroll.allow();
                }, 350);
            }
        },

        tip: function(html){
            var $Tip = null;
            if($('#dg-tip').length>0){
                return;
            }else{
                $Tip = $('<div id="dg-tip">'+html+'</div>');
            }
            $Tip.appendTo('body').fadeIn();
            setTimeout(function(){
                $Tip.fadeOut(function(){
                    $Tip.remove();
                });
            }, 2500);
        }
    },

    // 页面滚动事件
    pageScroll: {
        event: function(e){
            e.preventDefault();
        },

        // 禁止
        stop: function(){
            var fn = this.event;
            document.body.addEventListener('touchmove',fn,false);
        },

        // 允许
        allow: function(){
            var fn = this.event;
            document.body.removeEventListener('touchmove',fn,false);
        }
    },
    
    // 返回时间JSON，参数为秒
    timeJson: function(times) {
        var oTime = {};
        oTime.secs = Math.floor(times % 60);
        oTime.mins = Math.floor(times / 60 % 60);
        oTime.hours = Math.floor(times / 60 / 60);
        oTime.days = 0;

        if(oTime.hours > 23){
            oTime.days = Math.floor(oTime.hours/24);
            oTime.hours = oTime.hours - oTime.days*24;
        }
        if(oTime.secs<10){
            oTime.secs = '0' + oTime.secs;
        }
        if(oTime.mins<10){
            oTime.mins = '0' + oTime.mins;
        }
        if(oTime.hours<10){
            oTime.hours = '0' + oTime.hours;
        }
        if(oTime.days<10){
            oTime.days = '0' + oTime.days;
        }
        return oTime;
    },
    /* 请输入手机号 */
    regchcekPhone: function(){
        var that = this,
            $form = $("#reg_form"),
            $input = $form.find('input[name=mobile]'),
            $submit = $("#reg_submit");
        var check = that.check.isMobile;

        $submit.on("touchend",function(){
            var phone = $.trim($input.val());
            if(check(phone)){
                $.ajax({
                    type: 'post',
                    url: '/user/tel?random='+Math.random(),
                    data: {userTel:phone},
                    async:false,
                    dataType: 'json',
                    timeout: 500,
                    success: function(data){
                      if(data){
                    	  var str = BST.sendSmsCode(phone);
                    	  if(str == '发送成功') {
                    		  location.href="/mobile/set_authcode?user_tel="+phone;
                    	  }
                      }else{
                    	  BST.dialog.tip("该手机已被注册,请更换账号！");
                      }
                   },
                   error: function(xhr, type){
                      BST.dialog.tip("网络错误，请稍后再试！");
                   }
                });
            }else{
                that.dialog.tip("请输入正确的手机号");
            }
        });
    },
    /* 请输入验证码 */
    sendAuthCode: function(){
        var that = this,
            $reg = $("#reg_form"),
            $code = $reg.find("input[name=authcode]"),
            $reget = $("#regetbtn"),
            $down = $reget.find(".countdown"),
            $next = $("#next_step"),
            $phone = $('#phone').val();
        countdown(60);
        $reget.on("touchend",function(){
            var $this = $(this);
            if ($this.hasClass('btn-off')) {
                return false;
            }
            //发送验证码
            var str = BST.sendSmsCode($phone);
      	  	if(str == '发送成功') {
      	  		countdown(60);
      	  	}
        });
        $next.on('touchend', function(event) {
            var code = $.trim($code.val());
            if (code == '') {
                BST.dialog.tip("验证码不能为空！");
                return false;
            }
            if(!that.check.isNum(code)){
                BST.dialog.tip("验证码错误！");
                return false;
            }
            //检验验证码
            $.ajax({
              type: 'post',
              url: '/mobile/check_authcode',
              data: { code : code },
              dataType: 'json',
              async:false,
              timeout: 500,
              success: function(data){
            	  if(data) {
            		  location.href = "/mobile/set_passwrod?user_tel="+$phone;
            	  }else {
            		  BST.dialog.tip("验证码错误！");
            	  }
              },
              error: function(xhr, type){
                BST.dialog.tip("网络错误，请稍后再试！");
              }
            });
        });
        function countdown(num){
            num = parseInt(num);
            var timer = null,
                NUM = num;
            $reget.addClass('btn-off');
            $down.text('('+NUM+')').show();
            if(timer){
                clearInterval(timer);
                timer = null;
            }
            timer = setInterval(function(){
                num--;
                if(num == 0){
                    $reget.removeClass('btn-off');
                    $down.hide();
                    $down.text('('+NUM+')');
                    clearInterval(timer);
                    timer = null;
                    return;
                }
                $down.text('('+num+')')
            },1000); 
        };
    },
    /* 设置密码 */
    setPassWord: function(){
        var $reg = $("#reg_form"),
            $name = $reg.find('input[name=realName]'),
            $pw1 = $reg.find('input[name=userPassword]'),
            $pw2 = $reg.find('input[name=confirmPassword]'),
            $btn = $("#reg_submit"),
            userTel = $.trim($('#userTel').val());
        $btn.on('touchend', function(event) {
            var name = $.trim($name.val()),
                pw1 = $.trim($pw1.val()),
                pw2 = $.trim($pw2.val());
            if(name == ''){
                BST.dialog.tip("昵称不能为空！");
                return false;
            }
            if(pw1 == ''){
                BST.dialog.tip("密码不能为空！");
                return false;
            }
            if(pw1.length < 8 ){
                BST.dialog.tip("密码长度不能少于8位！");
                return false;
            }
            if(pw2 == ''){
                BST.dialog.tip("确认密码不能为空！");
                return false;
            }
            if(pw2.length < 8 ){
                BST.dialog.tip("确认密码长度不能少于8位！");
                return false;
            }
            if(pw2 !== pw1){
                BST.dialog.tip("两次密码不一致，请检查");
                $pw2.focus();
                return false;
            }
			var params = {
				userTel : userTel,
				realName : name,
				userPassword : pw1
			};
			
            //保存用户信息
			$.ajax({
			  type: 'post',
			  url: '/mobile/save_user',
			  data: params,
			  dataType: 'json',
			  async:false,
			  timeout: 500,
			  success: function(data){
				  if(data) {
					  location.href = "/success?user="+userTel+"&pwd="+pw1;
				  }else {
					  BST.dialog.tip("注册失败，请重试！");
				  }
			  },
			  error: function(xhr, type){
				  BST.dialog.tip("网络错误，请稍后再试！");
			  }
			});
        });
    },
    /*发送短信验证码*/
    sendSmsCode: function(phone) {
    	var message = '';
    	/*发送ajax请求短信验证码*/
        $.ajax({
            type: "post",
            url: "/user/getMsgCode?random="+Math.random(),
            data: {tel:phone},
            async : false,
            success: function(data){
                message = data.message;
                if(message=="发送失败"){
                	BST.dialog.tip("短信发送失败，请重试！");
                }else if(message=="每天最多只能发送三次"){
                	BST.dialog.tip("每天最多发三次");
                }else{
                	
                }
            }
        });
        
        return message;
    }
};


$(function(){
   BST.init();
});

